/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.dbutils

import com.google.inject.Inject
import cool.taomu.toolkit.annotations.datasource.Primary
import java.sql.Connection
import java.sql.SQLException
import java.util.List
import java.util.Map
import java.util.function.Function
import javax.sql.DataSource
import org.apache.commons.dbutils.QueryRunner
import org.apache.commons.dbutils.handlers.BeanListHandler
import org.apache.commons.dbutils.handlers.MapListHandler
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

@Accessors
class DbUtils extends QueryRunner {
    val static LOG = LoggerFactory.getLogger(DbUtils);

    Connection conn = null;

    DataSource ds

    @Inject
    new(@Primary DataSource ds) {
        this.ds = ds;
    }

    def void transaction(Function<DbUtils, Void> cl) {
        try {
            if (this.conn === null) {
                this.conn = ds.connection
            }
            LOG.info("执行数据库事务")
            this.conn.autoCommit = false;
            cl.apply(this)
            this.conn.commit;
        } catch (SQLException ex) {
            LOG.info("Sql  exception:", ex);
            this.conn.rollback;
        } finally {
            if (this.conn !== null) {
                this.close
            }
        }
    }

    override int update(String sql, Object ... args) {
        LOG.info("sql:{}", sql);
        if (this.conn === null) {
            this.conn = ds.connection
        }
        return this.update(conn, sql, args);
    }

    def int[] batch(String sql, List<List<Object>> args) {
        LOG.info("sql:{}", sql);
        if (this.conn === null) {
            this.conn = ds.connection
        }
        var Object[][] array = newArrayOfSize(args.size, 0);
        for (var int i = 0; i < array.size; i++) {
            array.set(i, args.get(i).toArray);
        }
        return this.batch(conn, sql, array);
    }

    def <T> List<T> queryEntity(String sql, Class<T> zlass, Object ... args) {
        LOG.info("sql:{}", sql);
        if (this.conn === null) {
            this.conn = ds.connection
        }
        var List<T> results = null;
        if (zlass !== null && !zlass.equals(Map)) {
            results = this.query(conn, sql, new BeanListHandler<T>(zlass), args);
        }
        return results;
    }

    def queryMap(String sql, Object ... args) {
        LOG.info("sql:{}", sql);
        if (this.conn === null) {
            this.conn = ds.connection
        }
        return this.query(conn, sql, new MapListHandler(), args);
    }

    def close() throws Exception {
        if (this.conn !== null) {
            LOG.info("关闭数据库连接")
            this.conn.close
            this.conn = null;
        }
    }

}
